package com.meida.module.arc.iam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cims.sync.constant.JsonResult;
import com.cims.sync.dto.AccountBean;
import com.cims.sync.dto.ApiPushDTO;
import com.cims.sync.dto.DeptBean;
import com.cims.sync.exception.BusinessException;
import com.cims.sync.exception.ErrorCode;
import com.cims.sync.util.MD5Util;
import com.cims.sync.util.SecurityUtil;
import com.cims.sync.util.SignUtil;
import com.meida.module.admin.client.entity.BaseAccount;
import com.meida.module.admin.provider.service.BaseAccountService;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.arc.iam.utils.JsonUtil;
import com.meida.module.system.client.entity.SysDept;
import com.meida.module.system.provider.service.SysDeptService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author wd
 * @Classname UserController
 * @Description None
 * @Date 2019/6/25 17:51
 */
@Controller
@RequestMapping("/push")
@Log4j2
public class PushController {

    @Value("${cims.appSecret}")
    private String appSecret;
    @Value("${cims.appId}")
    private String appId;

    @Autowired
    SysDeptService deptService;

    @Autowired
    BaseUserService baseUserService;
    @Autowired
    BaseAccountService baseAccountService;

    @RequestMapping(value = "/org")
    @ResponseBody
    public Object dept(@RequestBody ApiPushDTO apiPushDTO) {
        log.info("部门推送原始数据：" + JsonUtil.obj2json(apiPushDTO));
        String newSecret = MD5Util.getMD5String(appSecret);
        //检验签名
        String sign = SignUtil.getSign(appId, Long.valueOf(apiPushDTO.getTimestamp()), newSecret, "", "POST", new HashMap<>());
        if (!sign.equals(apiPushDTO.getSign())) {
            return JsonResult.err(ErrorCode.SIGN_CHECK_ERROR);
        }

        String data = SecurityUtil.decryptAES(apiPushDTO.getSyncData(), newSecret);

        List<DeptBean> deptBeans = JsonUtil.json2list(data, DeptBean.class);

        try {
            deptBeans.forEach(deptBean -> {
                log.info("收到部门数据：" + JsonUtil.obj2json(deptBean));
                if (DeptBean.MOD_STATUS.equals(deptBean.getStatus())) {
                    SysDept one = deptService.getOne(new QueryWrapper<SysDept>().lambda().eq(SysDept::getDeptCode, deptBean.getDepNum()));
                    if (one == null) {
                        one = new SysDept();
                        one.setDeptCode(deptBean.getDepNum());
                        one.setCreateTime(new Date());
                    }
                    if (StringUtils.isNotBlank(deptBean.getParentNum())) {
                        SysDept parent = deptService.getOne(new QueryWrapper<SysDept>().lambda().eq(SysDept::getDeptCode, deptBean.getParentNum()));
                        if (parent == null) {
                            throw new BusinessException(9001, "上级部门不存在:parentNum=" + deptBean.getParentNum());
                        }
                        one.setParentId(parent.getParentId());
                    }
                    one.setUpdateTime(new Date());
                    deptService.save(one);
                    log.info("保存部门数据成功：" + JsonUtil.obj2json(one));
                } else if (DeptBean.DEL_STATUS.equals(deptBean.getStatus())) {
                    SysDept one = deptService.getOne(new QueryWrapper<SysDept>().lambda().eq(SysDept::getDeptCode, deptBean.getDepNum()));
                    if (one != null) {
                        deptService.removeById(one);
                        log.info("删除部门数据成功：" + JsonUtil.obj2json(one));
                    } else {
                        log.info("删除部门数据失败：数据不存在");
                    }
                }
            });
        } catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.err(e.getErrCode(), e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.err(9001, e.getMessage());
        }
        return JsonResult.ok(apiPushDTO.getSign());
    }

    @RequestMapping(value = "/account")
    @ResponseBody
    public Object account(@RequestBody ApiPushDTO apiPushDTO) {
        log.info("账号推送原始数据：" + JsonUtil.obj2json(apiPushDTO));
        String newSecret = MD5Util.getMD5String(appSecret);
        String sign = SignUtil.getSign(appId, Long.valueOf(apiPushDTO.getTimestamp()), newSecret, "", "POST", new HashMap<>());
        if (!sign.equals(apiPushDTO.getSign())) {
            return JsonResult.err(ErrorCode.SIGN_CHECK_ERROR);
        }

        String data = SecurityUtil.decryptAES(apiPushDTO.getSyncData(), newSecret);

        List<AccountBean> accountBeans = JsonUtil.json2list(data, AccountBean.class);

        try {
            accountBeans.forEach(accountBean -> {
                log.info("收到账号数据：" + JsonUtil.obj2json(accountBean));
                if (AccountBean.NORMAL_STATUS.equals(accountBean.getStatus())) {
                    BaseAccount accountInfo = baseAccountService.getAccount(accountBean.getPrincipalId());
                    if (accountInfo == null) {
                        accountInfo = new BaseAccount();
                        accountInfo.setAccount(accountBean.getPrincipalId());
                        accountInfo.setCreateTime(new Date());
                    }
                    accountBean.getDeptNums().forEach(deptNum -> {
                        if (StringUtils.isNotBlank(deptNum)) {
                            SysDept deptInfo = deptService.getOne(new QueryWrapper<SysDept>().lambda().eq(SysDept::getDeptCode, accountBean.getDeptNums().get(0)));
                            if (deptInfo == null) {
                                throw new BusinessException(9001, "推送账号数据所属部门不存在：deptNum=" + deptNum);
                            }
                        }
                    });

                    accountInfo.setUpdateTime(new Date());
                    baseAccountService.save(accountInfo);
                    log.info("保存账号数据成功：" + JsonUtil.obj2json(accountInfo));
                } else if (AccountBean.DELETE_STATUS.equals(accountBean.getStatus())
                        || AccountBean.DISABLE_STATUS.equals(accountBean.getStatus())) {
                    BaseAccount accountInfo = baseAccountService.getAccount(accountBean.getPrincipalId());
                    if (accountInfo != null) {
                        baseAccountService.removeById(accountInfo);
                        log.info("删除账号数据成功：" + JsonUtil.obj2json(accountInfo));
                    } else {
                        log.info("删除账号数据失败：数据不存在");
                    }
                }
            });
        } catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.err(e.getErrCode(), e.getErrMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.err(9001, e.getMessage());
        }
        return JsonResult.ok(apiPushDTO.getSign());
    }
}
